<template>
  <div>
    <el-row>
      <el-col :span="8">
        <el-select
          v-model="value"
          placeholder="选择书籍"
          clearable
          @change="getThisBookPing"
        >
          <el-option
            v-for="item in books"
            :key="item._id"
            :label="item.bookname"
            :value="item._id"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-button v-show="this.value != ''" @click="openHei">查看黑名单</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <div class="ping">
          <li v-for="item in allPing" :key="item._id">
            <div class="PA">
              <span
                v-if="item.state == 1"
                style="color:green"
                @click="changePingState(item._id, item.state)"
                >{{ item.date }}</span
              >
              <span
                v-if="item.state == 0"
                style="color:red"
                @click="changePingState(item._id, item.state)"
                >{{ item.date }}</span
              >
              <span style="color:blue" @click="toBook">去往评论区</span>
            </div>
            <div class="PB">
              <h4 @click="toUser(item.userid)">{{ item.username }}:</h4>
              <span>{{ item.text }}</span>
            </div>
            <div class="PC">
              <span @click="replyMsg(item._id,item.beforeid,item.username)">回复</span>
              <span
                v-if="thisBookHei.includes(item.userid)"
                @click="pullHei(item.userid)"
                >移除黑名单</span
              >
              <span
                v-if="!thisBookHei.includes(item.userid)"
                @click="addHei(item.userid)"
                >拉黑</span
              >
              <span @click="removePing(item._id, item.beforeid)">删除</span>
            </div>
          </li>
          <!-- 分页 -->
          <div class="block" v-if="this.value != ''">
            <span class="demonstration">共有{{ isLength }}条记录</span>
            <el-pagination
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              layout="prev, pager, next, jumper"
              :page-size="10"
              :total="isLength"
            >
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 黑名单对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="heiDialogVisible"
      width="30%"
    >
    <div >
        <el-checkbox-group v-model="checkList" class="heiDiv">
        <el-checkbox :label="item._id" v-for="item in allHei" :key="item._id">
          {{item.username}}
        </el-checkbox>
        </el-checkbox-group>
    </div>
      <!-- {{this.allHei}} -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="heiDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subPullHei"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getBookList();
    this.getThisBookPing();
  },
  data() {
    return {
      heiDialogVisible:false,
      books: [],
      value: "",
      allPing: [],
      thisBookHei: [],
      allHei:[],
      checkList:[],
      isLength: 0,
      currentPage: 1,
      pageSize: 10,
    };
  },
  methods: {
    //路由
    toBook() {
      let routeUrl = this.$router.resolve(`/tobook/${this.value}`);
      window.open(routeUrl.href, "_blank");
    },
    toUser(id) {
      let routeUrl = this.$router.resolve(`/touser/${id}`);
      window.open(routeUrl.href, "_blank");
    },

    async getBookList() {
      const { data: res } = await this.$http.get(
        `/books/writerbook/${window.sessionStorage.getItem("writerId")}`
      );
      //console.log(res);
      if (res.status != 200) return this.$message.error("获取失败");
      this.books = res.data;
    },
    async getThisBookPing() {
      //console.log(this.value == '');
      if (this.value == "") {
        // const {data:res} = await this.$http.get(`/ping/allPingByWriterId/${window.sessionStorage.getItem("writerId")}`)
        //this.allPing = res.data;
        //console.log(res);
        this.allPing = [];
        return;
      } else {
        const { data: red } = await this.$http.get(
          `/books/thisBookHei/${this.value}`
        );
        this.thisBookHei = red.data.hei;
        //console.log(this.thisBookHei);
        const { data: res } = await this.$http.post(
          `/ping/allPingByBookId/${this.value}`,
          {
            pageSize: this.pageSize,
            currentPage: this.currentPage,
          }
        );
        this.isLength = res.num;
        this.allPing = res.data;
        return;
      }
      //console.log(this.value);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getThisBookPing();
    },
    replyMsg(id,beforeid,name) {
      this.$prompt('请输入回复内容', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(async ({ value }) => {
          if(beforeid == 0){
             const { data: res } = await this.$http.post(
            `/ping/secHuiFu/${window.sessionStorage.getItem("writerId")}`,
            {
              bookid: this.value,
              writerid: window.sessionStorage.getItem("writerId"),
              beforeid: id,
              text: `作者回复-@${name}:${value}`,
              ava: window.sessionStorage.getItem("writerAvatar"),
              name: window.sessionStorage.getItem("writerName")
            })
            this.getThisBookPing();
          }
          if(beforeid != 0){
             const { data: res } = await this.$http.post(
            `/ping/secHuiFu/${window.sessionStorage.getItem("writerId")}`,
            {
              bookid: this.value,
              writerid: window.sessionStorage.getItem("writerId"),
              beforeid: beforeid,
              text: `作者回复-@${name}:${value}`,
              ava: window.sessionStorage.getItem("writerAvatar"),
              name: window.sessionStorage.getItem("writerName")
            })
            this.getThisBookPing();
          }

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });       
        });
    },
    async removePing(id, before) {
      if (before == 0) {
        this.$confirm(
          "此评论为顶级评论，删除将删除所有子评论, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            const {
              data: res,
            } = await this.$http.delete(`/ping/deletePing/${id}`, {
              beforeid: before,
            });
            if (res == "OK") {
              this.getThisBookPing();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message.error("删除失败");
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      } else {
        const { data: res } = await this.$http.delete(
          `/ping/deletePing/${id}`,
          { beforeid: before }
        );
        if (res == "OK") {
          this.getThisBookPing();
        }
        //console.log(res);
      }
    },
    async changePingState(id, state) {
      //console.log(state);
      const { data: res } = await this.$http.post(
        `/ping/changePingState/${id}`,
        { state: state }
      );
      if (res == "OK") {
        this.getThisBookPing();
        return;
      } else {
        this.$message.error("操作失败");
      }
    },
    async addHei(id) {
      const { data: res } = await this.$http.post(
        `/books/addHei/${this.value}`,
        { id: id }
      );
      if (res == "OK") {
        this.getThisBookPing();
        return;
      }
    },
    async pullHei(id) {
      const {
        data: res,
      } = await this.$http.post(`/books/pullHei/${this.value}`, { id: id });
      if (res == "OK") {
        this.getThisBookPing();
        return;
      }
    },
    async openHei(){
      this.heiDialogVisible = true;
      const {
        data: res,
      } = await this.$http.get(`/users/thisBookHei/${this.value}`);
      this.allHei = res.data;
    },
    async subPullHei(){
       const {
        data: res,
      } = await this.$http.post(`/books/pullManyHei/${this.value}`, { id: this.checkList });
      if (res == "OK") {
        this.getThisBookPing();
        this.heiDialogVisible = false;
        this.checkList = [];
        return;
      }
    }
  },
};
</script>

<style lang="less" scoped>
li {
  list-style: none;
}
.ping {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}
.ping li {
  width: 100%;
  height: 150px;
  display: flex;
  flex-direction: column;
  border-style: dashed;
  border-width: 0px 0px 1px 0px;
}
.PA {
  height: 30px;
  width: 100%;
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.PA span:hover {
  cursor: pointer;
}
.PB {
  height: 100px;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
.PB h4 {
  margin: 0px 5px 0px 0px;
}
.PB h4:hover {
  color: blue;
  cursor: pointer;
}
.PC {
  height: 20px;
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
.PC span {
  margin-left: 5px;
  margin-right: 5px;
}
.PC span:hover {
  color: blue;
  cursor: pointer;
}
.heiDiv{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
